import {defineStore} from "pinia";

import {reqAdminInfo} from "@/api";
import {h, ref} from "vue";
import {RouterLink} from "vue-router";

const useAdminStore = defineStore('admin', () => {

    const adminInfo = ref({})
    const menuOptions = ref([])

    async function loadAdminInfo() {
        const getLabel = (info) => {
            return () => h(RouterLink, {
                to: {name: info.resourceKey},
            }, {default: () => info.resourceLabel})
        }
        const getMenu = (menuList) => {
            const resList = []
            menuList.forEach(info => {
                resList.push({
                    label: getLabel(info),
                    key: info.resourceKey,
                })
            })
            return resList
        }

        const resp = await reqAdminInfo()
        adminInfo.value = resp.data

        menuOptions.value = []
        menuOptions.value.push({
            label: getLabel({resourceKey: 'Home', resourceLabel: '首页'}),
            key: 'Home'
        })
        if (adminInfo.value.menuAuthList) {
            adminInfo.value.menuAuthList.forEach(info => {
                if (info.childList && info.childList.length > 0) {
                    menuOptions.value.push({
                        label: info.resourceLabel,
                        key: info.resourceKey,
                        children: getMenu(info.childList)
                    })
                } else {
                    menuOptions.value.push({
                        label: getLabel(info),
                        key: info.resourceKey,
                    })
                }
            })
        }
    }
    return {
        adminInfo,
        menuOptions,
        loadAdminInfo
    }
})

export default useAdminStore